package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.vo.BackUserVo;
import com.heima.model.user.vo.UserVo;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //用户信息返回封装
        UserVo userVo = new UserVo();
        //若是以用户身份登录，判断用户是否可用
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName, dto.getName())
                .eq(WmUser::getPassword, dto.getPassword()));

        //若是存在则生成JWT,不存在则拒绝生成
        if (ObjectUtil.isNotEmpty(wmUser)) {
            String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
            BackUserVo backUserVo = new BackUserVo();
            BeanUtil.copyProperties(wmUser,backUserVo );
            userVo.setUser(backUserVo);
            userVo.setToken(token);
            return ResponseResult.okResult(userVo);
        }
        return ResponseResult.errorResult(401, "用户不存在");

//        //用户信息返回封装
//        UserVo userVo = new UserVo();
//        //若是以用户身份登录，判断是否存在该用户
//        //若是存在，则生成JWT，若是不存在，则拒绝生成
//        if (ObjectUtil.isNotEmpty(dto) && StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {
//            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).eq(ApUser::getPassword, dto.getPassword()));
//            if (ObjectUtil.isNotEmpty(apUser)) {
//                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
//                userVo.setUser(BackUserVo
//                        .builder()
//                        .id(Long.valueOf(apUser.getId()))
//                        .name(apUser.getName())
//                        .phone(apUser.getPhone())
//                        .build());
//                userVo.setToken(token);
//                return ResponseResult.okResult(userVo);
//            }
//            throw new RuntimeException("用户不存在");
//        }
//        //若是以游客身份登录，直接返回JWT
//        String token = AppJwtUtil.getToken(1L);
//        userVo.setToken(token);
    }
}